<template>
  <el-dialog :title="title" :visible.sync="visible" width="800px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="模板名称" prop="templateName" key="templateName">
        <el-row>
          <el-col :span="12">
            <el-input v-model="form.templateName" placeholder="请输入模板名称" maxlength="20" show-word-limit/>
          </el-col>
          <el-col :span="11">
            <el-button type="text" @click="handleSelectTemplate" style="margin-left: 10px;">使用公共模板</el-button>
            <el-button type="text" @click="cancelSelectTemplate" v-if="form.publicMessageId">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="推送渠道" prop="ordinaryMessageType" key="ordinaryMessageType">
        <el-radio-group v-model="form.ordinaryMessageType" size="mini" @change="handleSelectOrdinaryMessageType">
          <el-radio-button label="1">应用外</el-radio-button>
          <el-radio-button label="2">应用内</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="pushChannel" key="pushChannel">
        <el-checkbox-group v-model="pushChannel" @change="handleSelectPushChannel"
                           v-if="form.ordinaryMessageType === '1'"
        >
          <el-checkbox v-for="item in pushChannelList" :label="item.value" :key="item.value" :disabled="item.disabled">
            {{
              item.label
            }}
          </el-checkbox>
        </el-checkbox-group>
        <el-radio-group v-model="form.pushChannel" size="mini" v-if="form.ordinaryMessageType === '2'"
                        @change="handleSelectPushChannel"
        >
          <el-radio v-for="item in pushChannelList" :label="item.value" :key="item.value" :disabled="item.disabled">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="标题" prop="messageHeader">
        <el-input v-model="form.messageHeader" placeholder="请输入消息标题" :disabled="!!form.publicMessageId"/>
      </el-form-item>
      <el-form-item label="内容" prop="messageContent">
        <el-input type="textarea" v-model="form.messageContent" placeholder="请输入消息内容" rows="4" maxlength="200"
                  show-word-limit :disabled="!!form.publicMessageId"
        />
      </el-form-item>
      <el-form-item label="触发行为" prop="triggeringBehavior">
        <el-radio-group v-model="form.triggeringBehavior" size="mini" @change="handleSelectTriggeringBehavior">
          <el-radio-button label="1">立即推送</el-radio-button>
          <el-radio-button label="2">定时推送</el-radio-button>
          <el-radio-button label="3" disabled>重复推送</el-radio-button>
          <el-radio-button label="4">指定条件推送</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="triggeringTime" key="triggeringTime" v-if="form.triggeringBehavior === '2'">
        <el-date-picker v-model="form.triggeringTime" type="datetime" placeholder="请选择触发时间"
                        format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item prop="pushConditionCode" key="pushConditionCode" v-if="form.triggeringBehavior === '4'">
        <el-select v-model="form.pushConditionCode" placeholder="请选择推送条件" clearable filterable>
          <el-option v-for="item in pushConditionList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-tooltip class="item" effect="dark" content="基于行为条件作接口绑定触发推送消息。比如：工单超时处理触发推送。"
                    placement="top-start"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>

      </el-form-item>
      <el-form-item label="目标人群" prop="ordinaryMessageUserList" key="ordinaryMessageUserList">
        <el-button type="primary" @click.stop="handleSelectUser"
                   :disabled="form.triggeringBehavior === '4'"
        >{{
            (form.ordinaryMessageUserList && form.ordinaryMessageUserList.length) ? '修改' : '选择'
          }}用户
        </el-button>
      </el-form-item>
      <el-form-item label="状态" prop="ordinaryMessageState">
        <el-radio-group v-model="form.ordinaryMessageState" size="mini">
          <el-radio label="0">启用</el-radio>
          <el-radio label="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!--  公共模板选择弹窗  -->
    <public-template :show.sync="showPublicTemplate" @success="handleSelectPublicTemplate"></public-template>
    <!--  用户选择弹窗  -->
    <select-user :show.sync="showSelectUser" @success="handleSelectUserSuccess"
                 :selected-data="form.ordinaryMessageUserList" :data="form"
    ></select-user>
  </el-dialog>
</template>

<script>
import { debounce } from '@/utils'
import { addMessage, updateMessage } from '@/api/messageCenter/ordinaryMessage'
import publicTemplate from './publicTemplate.vue'
import selectUser from './selectUser.vue'
import { listPushConditionByDepartment } from '@/api/messageCenter/pushCondition'
import { getChannelByTenantId } from '@/api/messageCenter/channel'

export default {
  name: 'add',
  components: {
    publicTemplate,
    selectUser
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '新增消息模板'
    },
    data: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      //推送渠道
      pushChannel: [],
      //推送条件列表
      pushConditionList: [],
      //公共模板选择弹窗
      showPublicTemplate: false,
      //用户选择弹窗
      showSelectUser: false,
      //渠道详情
      channelDetail: {},
      //表单
      form: {},
      // 表单校验
      rules: {
        tenantId: [
          { required: true, message: '请选择机构', trigger: ['change', 'blur'] }
        ],
        tenantName: [
          { required: true, message: '请输入机构名称', trigger: ['change'] }
        ],
        ordinaryMessageType: [
          { required: true, message: '请选择消息类型', trigger: ['change', 'blur'] }
        ],
        pushChannel: [
          { required: true, message: '请选择推送渠道', trigger: ['blur'] }
          // {
          //   validator: (rule, value, callback) => {
          //     console.log('this.form.pushChannel', this.form.pushChannel)
          //     if (!value) {
          //       callback(new Error('请选择推送渠道'))
          //     }
          //     callback()
          //   }, trigger: 'blur'
          // }
        ],
        templateName: [
          { required: true, message: '请输入模板名称', trigger: ['change', 'blur'] }
        ],
        messageHeader: [
          { required: true, message: '请输入消息标题', trigger: ['change', 'blur'] }
        ],
        messageContent: [
          { required: true, message: '请输入消息内容', trigger: ['change', 'blur'] }
        ],
        triggeringBehavior: [
          { required: true, message: '请选择触发行为', trigger: ['change', 'blur'] }
        ],
        triggeringTime: [
          { required: true, message: '请选择触发时间', trigger: ['change', 'blur'] }
        ],
        pushConditionCode: [
          { required: true, message: '请选择推送条件', trigger: ['change', 'blur'] }
        ],
        ordinaryMessageUserList: [
          {
            validator: (rule, value, callback) => {
              if (value.length === 0 && this.form.triggeringBehavior !== '4') {
                callback(new Error('请选择目标人群'))
              } else {
                callback()
              }
            },
            trigger: 'change',
            required: true,
          }
        ],
        ordinaryMessageState: [
          { required: true, message: '请选择状态', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    },
    // 推送渠道列表
    pushChannelList() {
      if (this.form.ordinaryMessageType === '1') {
        return [{ label: '企业微信', value: '1', disabled: this.channelDetail.wechatState === '1' }, {
          label: '钉钉',
          value: '2',
          disabled: this.channelDetail.dingState === '1'
        }].filter(item => item.disabled === false)
      }
      if (this.form.ordinaryMessageType === '2') {
        return [{ label: '商家小程序', value: '3' }, { label: '租客小程序', value: '4' }]
      }
      return []
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.reset()
      }
    }
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        // tenantId: "", //机构id
        // tenantName: "", //机构名称
        templateName: '', //模板名称
        ordinaryMessageType: '1', //普通消息类型：1.应用外，2.应用内
        pushChannel: '', //推送渠道：1.企业微信，2.钉钉，3.商家小程序，4.租客小程序(多选的话,用英文逗号拼接)
        pushChannelName: '', //推送渠道名称(多选的话,用英文逗号拼接)
        messageHeader: '', //消息标题
        messageContent: '', //消息内容
        triggeringBehavior: '1', //触发行为：1.立即推送，2.定时推送，3.重复推送，4.指定条件推送
        triggeringTime: '', //触发时间
        pushConditionCode: '', //推送条件编码
        ordinaryMessageState: '0', //状态：0.启用，1.禁用
        ordinaryMessageUserList: [], //目标人群
        publicMessageId: '' //公共模板id
      }
      this.pushChannel = []
      this.getPushConditionCode()
      this.getPushChannelDetail()
      this.resetForm('form')
      if (this.data.ordinaryMessageId != null) {
        this.$nextTick(() => {
          this.form = { ...this.data }
          if (this.form.ordinaryMessageType === '1') {
            this.pushChannel = this.form.pushChannel ? this.form.pushChannel.split(',') : []
          } else if (this.form.ordinaryMessageType === '2') {
            this.form.pushChannel = this.data.pushChannel
          }
          this.form.triggeringTime = new Date(this.form.triggeringTime) || ''
          // this.getPushConditionCode()
          // this.getPushChannelDetail()
        })

      }
    },
    // 获取渠道详情
    getPushChannelDetail() {
      getChannelByTenantId().then(response => {
        console.log('response', response)
        this.channelDetail = response.data
      })
    },
    // 获取指定条件的推送条件编码
    getPushConditionCode() {
      if (this.form.ordinaryMessageType) {
        let params = {
          messageType: this.form.ordinaryMessageType
        }
        listPushConditionByDepartment(params).then(response => {
          this.pushConditionList = response.data.map(item => {
            return {
              label: item.conditionName,
              value: item.pushConditionCode
            }
          })
        })
      }

    },
    // 选择普通消息类型
    handleSelectOrdinaryMessageType(value) {
      this.form.pushChannel = ''
      this.form.pushChannelName = ''
      this.pushChannel = []
      // 清空目标人群
      this.form.ordinaryMessageUserList = []
      if (value) {
        this.getPushConditionCode()
      }
    },
    // 选择公共模板
    handleSelectTemplate() {
      this.showPublicTemplate = true
    },
    // 取消选择公共模板
    cancelSelectTemplate() {
      this.form.publicMessageId = ''
      this.form.messageHeader = ''
      this.form.messageContent = ''
    },
    // 选择推送渠道
    handleSelectPushChannel(ids) {
      // 清空目标人群
      this.form.ordinaryMessageUserList = []

      console.log('ids', ids)
      ids = Array.isArray(ids) ? ids : [ids]
      this.form.pushChannel = ids.join(',')
      let pushChannelName = this.pushChannelList.filter(item => ids.includes(item.value))
      this.form.pushChannelName = pushChannelName.map(item => item.label).join(',')
    },
    // 选择公共模板
    handleSelectPublicTemplate(data) {
      console.log('data', data)
      this.form.templateName = data[0].templateName
      this.form.messageHeader = data[0].messageHeader
      this.form.messageContent = data[0].messageContent
      this.form.publicMessageId = data[0].publicMessageId
      this.showPublicTemplate = false
    },
    // 触发行为改变
    handleSelectTriggeringBehavior(value) {
      this.form.triggeringTime = ''
      this.form.ordinaryMessageUserList = []
    },
    // 选择用户
    handleSelectUser() {
      if (!this.form.pushChannel) {
        this.$modal.msgError('请选择推送渠道')
        return
      }
      this.showSelectUser = true
    },
    handleSelectUserSuccess(data) {
      console.log('data', data)
      this.form.ordinaryMessageUserList = data.map(item => {
        return {
          userId: item.userId,
          userName: item.userName,
          userPhone: item.phonenumber ? item.phonenumber : item.userPhone
        }
      })
    },
    // 表单提交
    /** 提交按钮 */
    submitForm: debounce(function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let params = { ...this.form }
          params.triggeringTime = params.triggeringTime ? this.formatDate(params.triggeringTime, 'YYYY-MM-DD HH:mm:ss') : ''
          if (this.form.ordinaryMessageId != null) {
            updateMessage(params).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.cancel()
              this.$emit('success')
            })
          } else {
            addMessage(params).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.cancel()
              this.$emit('success')
            })
          }
        }
      })
    }, 500, true),
    // 取消按钮
    cancel() {
      this.visible = false
      this.reset()
    }
  }
}
</script>

<style scoped lang="scss">

</style>
